package com.situ.gym.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.situ.gym.pojo.Role;
import com.situ.gym.pojo.query.RoleQuery;
import com.situ.gym.service.IRoleService;
import com.situ.gym.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Gao
 * @since 2025-09-01
 */
@RestController
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService roleService;

    @GetMapping("/selectAll")
    public Result<List<Role>> selectAll() {
        List<Role> list = roleService.list();
        return Result.ok(list);
    }

    //Restful    GET(查找)、POST(添加)、DELETE(删除)、PUT(修改)
    //@RequestMapping("/list")
    //@RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
    //@RequestMapping(value = "/list", method = RequestMethod.GET)
    @GetMapping("/list")
    public Result<IPage<Role>> list(RoleQuery roleQuery) {
        System.out.println("RoleController.list");
        IPage<Role> page = roleService.list(roleQuery);
        return Result.ok(page);
    }

    // /deleteById?id=1
    // /deleteById/1
    @DeleteMapping("/deleteById/{id}")
    public Result deleteById(@PathVariable Integer id) {
        roleService.removeById(id);
        return Result.ok("删除成功");
    }

    // /deleteAll/1,2,3
    @DeleteMapping("/deleteAll/{ids}")
    public Result deleteAll(@PathVariable Integer[] ids) {
        //roleService.removeBatchByIds(Arrays.asList(ids));
        roleService.deleteAll(ids);
        return Result.ok("删除成功");
    }

    /*@PostMapping("/add")
    public Result add(Role role) {
        System.out.println(role);
        return Result.ok();
    }*/

    // @RequestBody : 封装前台传递过来的JSON格式数据
    // @ResponseBody : 将数据转换为JSON格式返回
    @PostMapping("/add")
    public Result add(@RequestBody Role role) {
        System.out.println(role);
        roleService.save(role);
        return Result.ok("添加成功");
    }

    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        Role role = roleService.getById(id);
        return Result.ok(role);
    }

    @PutMapping("/update")
    public Result update(@RequestBody Role role) {
        System.out.println(role);
        //roleService.saveOrUpdate(role);
        roleService.updateById(role);
        return Result.ok("更新成功");
    }

    @GetMapping("/selectAssignedPermission/{roleId}")
    public Result<Map<String, Object>> selectAssignedPermission(@PathVariable Integer roleId) {
        Map<String, Object> map = roleService.selectAssignedPermission(roleId);
        return Result.ok(map);
    }

    @PostMapping("/assignPermission")
    public Result assignPermission(Long roleId, Long[] permissionIds) {
        roleService.assignPermission(roleId, permissionIds);
        return Result.ok("分配成功");
    }

}

